package com.xiaolin.springsecurity.controller;

import com.xiaolin.springsecurity.model.SystemUser;
import com.xiaolin.springsecurity.service.SystemUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

/**
 * @author xiaolin
 * @description 描述
 * @since 2024/5/7
 */
@Controller
@RequestMapping("/user")
public class SystemUserController {

    @Autowired
    private SystemUserService systemUserService;

    /**
     * 获取用户信息
     *
     * @param model
     * @return
     */
    @PreAuthorize("hasAnyRole('admin','common')")
    @GetMapping("/getUserInfo")
    public String getUserInfo(Model model) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String username = authentication.getName();
        SystemUser user = systemUserService.getUser(username);
        model.addAttribute("user", user);
        return "user";
    }

    @PreAuthorize("hasRole('admin')")
    @GetMapping("/getUserList")
    public String getUserList(Model model) {
        List<SystemUser> users = systemUserService.getUsers();
        model.addAttribute("users", users);
        return "userList";
    }

}
